package com.kaikeba.estack.common.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.kaikeba.estack.exception.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据源相关配置
 *
 * @author xingwan
 */
public class DataSourceUtil {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);

    private static DataSource dataSource;

    static {
        try {
            Properties ppt = new Properties();
            ppt.load(DataSourceUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(ppt);
        } catch (Exception e) {
            logger.error("在classpath下加载数据源配置文件[jdbc.properties]失败", e);
        }
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException sqlException) {
            throw new DataAccessException(sqlException);
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 关闭数据库连接
     *
     * @param connection 数据库连接对象
     */
    public static void close(Connection connection) {
        if (connection != null) {
            try {
                if (connection.isClosed()) {
                    return;
                }
                connection.close();
            } catch (Exception var2) {
                logger.error("close connection error", var2);
            }

        }
    }

    /**
     * 关闭Statement对象
     *
     * @param statement
     */
    public static void close(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception var2) {
                logger.error("close statement error", var2);
            }

        }
    }

    /**
     * 关闭ResultSet对象
     *
     * @param resultSet
     */
    public static void close(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception var2) {
                logger.error("close result set error", var2);
            }

        }
    }
}
